package com.pkk.penguin.frame.know.java.driven.condition.importbean.importbeandefinition;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

/**
 * @description: 自定义的自定义配置类
 * @author: peikunkun
 * @create: 2020-07-31 16:57
 **/
@Slf4j
public class MyImportBeanDefinition implements ImportBeanDefinitionRegistrar {

  /**
   * Register bean definitions as necessary based on the given annotation metadata of the importing {@code
   *
   * @param importingClassMetadata annotation metadata of the importing class【导入类的注释元数据信息】
   * @param registry current bean definition registry:【注册bean】
   * @Configuration} class.
   * <p>Note that {@link BeanDefinitionRegistryPostProcessor} types may <em>not</em> be
   * registered here, due to lifecycle constraints related to {@code @Configuration} class processing.
   */
  @Override
  public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
    final boolean window = registry.containsBeanDefinition("window");
    log.info("是否包含[window]bean?" + window + "，包含该bean将会注入WindowDrivenBean");
    if (window) {
      //定义beanDefinition
      BeanDefinition beanDefinition = new RootBeanDefinition(WindowDrivenBean.class);

      //注册一个bean
      registry.registerBeanDefinition("windowDrivenBean", beanDefinition);

      final boolean windowDrivenBean = registry.containsBeanDefinition("windowDrivenBean");
      log.info("是否包含[windowDrivenBean]bean?" + windowDrivenBean + (
          windowDrivenBean ? "包含,将会更名为windowDrivenBeanAlias" : "不操作"));
      if (windowDrivenBean) {
        //给一个bean起一个别名
        registry.registerAlias("windowDrivenBean", "windowDrivenBeanAlias");
        log.info("再次验证是否包含[windowDrivenBean]bean?" + registry.containsBeanDefinition("windowDrivenBean"));
        log.info("验证是否包含[windowDrivenBeanAlias]bean?" + registry.containsBeanDefinition("windowDrivenBeanAlias"));

        final String[] windowDrivenBeans = registry.getAliases("windowDrivenBean");
        log.info("-->" + JSONObject.toJSONString(windowDrivenBeans));
      }
    }
  }
}
